package com.hula.loan4u.net;

import android.content.Context;

import com.hula.loan4u.utils.AppUtils;
import com.hula.loan4u.utils.LogUtil;
import com.hula.loan4u.view.LoadingDialog;
import com.zhy.http.okhttp.callback.StringCallback;

import okhttp3.Call;
import okhttp3.Request;

public abstract class LoadingStringCallBack extends StringCallback {
    private LoadingDialog loadingDialog;
    private Context mContext;

    public LoadingStringCallBack(Context context, boolean showLoading) {
        try {
            mContext = context;
            if (showLoading && context != null) {
                loadingDialog = new LoadingDialog(context);
            }
        } catch (Exception e) {
            LogUtil.printeException(e);
        }
    }

    @Override
    public void onResponse(String response, int id) {
        onResponse(response);
    }

    @Override
    public void onError(Call call, Exception e, int id) {
        if (!AppUtils.isNetworkConnected(mContext)) {
            onError("无网络连接");
        } else {
            if (!call.isCanceled()) {
                LogUtil.e("LoadingStringCallBack", e.toString());
                onError("服务器异常:" + e.getMessage());
            }
        }
    }

    public abstract void onResponse(String response);

    public abstract void onError(String errorMessage);

    @Override
    public void onAfter(int id) {
        super.onAfter(id);
        try {
            if (loadingDialog != null && loadingDialog.isShowing()) {
                loadingDialog.dismiss();
            }
        } catch (Exception e) {
            LogUtil.printeException(e);
        }
    }

    @Override
    public void onBefore(Request request, int id) {
        super.onBefore(request, id);
        try {
            if (loadingDialog != null && !loadingDialog.isShowing()) {
                loadingDialog.show();
            }
        } catch (Exception e) {
            LogUtil.printeException(e);
        }
    }

}
